package com.origin.app.business.net

import android.util.Log
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.origin.app.MyApplication
import com.origin.app.bean.WeatherBean
import com.origin.baselibrary.viewmodel.BaseViewModel
import com.origin.netlibrary.NetUtils.getNet
import com.origin.netlibrary.listener.DownloadListener
import com.origin.netlibrary.listener.Response
import com.origin.netlibrary.netapi.DownloadService
import com.origin.netlibrary.netapi.RequestFormat
import com.origin.netlibrary.requestDownload
import kotlinx.coroutines.delay
import java.io.File

class NetViewModel : BaseViewModel() {

    val progressInfo = MutableLiveData<String>()
    private val restService: RequestFormat by lazy {
        MyApplication.getInstance().retrofitManager.requestFormat
    }
    private val downloadService: DownloadService by lazy {
        MyApplication.getInstance().retrofitManager.downloadService
    }

    fun netRequest(log: ObservableField<String>) {
        viewModelSuspend {
            val map = mapOf("city" to "北京", "key" to "6c11b7969beec525c7bb8530e39f4442")
            val weatherBean = restService.post("http://apis.juhe.cn/simpleWeather/query", map).getNet(this, object : Response<WeatherBean>() {});
            delay(3000)
            log.set(weatherBean.reason)
        }
    }

    fun netDownload(file: File) {

        viewModelSuspend {

            downloadService
                .download("http://6dec0a507ef02e68764ac609008b775b.dlied1.cdntips.net/downv6.qq.com/qqweb/QQ_1/android_apk/Android_8.8.88.7830_537118044_HB.32.apk?mkey=626a66c1af981557&f=0000&cip=175.152.51.162&proto=https&access_type=")
                .requestDownload(file.absolutePath,
                    object : DownloadListener {
                        override fun onStart(netUrl:String) {

                        }

                        override fun onFail(exceptionStr: String,netUrl:String) {

                        }

                        override fun onProgress(downloadProgress: Int, speed: String,netUrl:String) {
                            Log.e("下载进度", "$downloadProgress 下载速度 $speed")
                            progressInfo.postValue("下载进度 $downloadProgress 下载速度 $speed")
                        }


                        override fun onFinish(downloadPath: String,netUrl:String) {

                        }

                    })
        }


    }
}